package com.example.weight.greenSeasons;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class BangongShiyanYongdian extends AppCompatActivity {

    private TitleBar titleBar;
    //日期
    Calendar calendar=Calendar.getInstance(Locale.CHINA);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;

    private EditText zongdiankongxiang,jizhuangxiangsushe_yiceng,jizhuangxiangsushe_erceng,jizhuangxiangsushe_sanceng_dong,jizhuangxiangsushe_sanceng_xi,shiyanshimenting,bangongshi1,bangongshi2,bangongshi3,bangongshi4,shebeidongligui,kufangpeidianxiang,xinzhanbiandianshi,chufangneidianxiang;

    //用户、抄表人
    private String name,factory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bangong_shiyan_yongdian);

        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                BangongShiyanYongdian.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        //日期
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));
        //表读数
        zongdiankongxiang=findViewById(R.id.zongdiankongxiang);
        jizhuangxiangsushe_yiceng=findViewById(R.id.jizhuangxiangsushe_yiceng);
        jizhuangxiangsushe_erceng=findViewById(R.id.jizhuangxiangsushe_erceng);
        jizhuangxiangsushe_sanceng_dong=findViewById(R.id.jizhuangxiangsushe_sanceng_dong);
        jizhuangxiangsushe_sanceng_xi=findViewById(R.id.jizhuangxiangsushe_sanceng_xi);
        bangongshi1=findViewById(R.id.bangongshi1);
        bangongshi2=findViewById(R.id.bangongshi2);
        bangongshi3=findViewById(R.id.bangongshi3);
        bangongshi4=findViewById(R.id.bangongshi4);
        shiyanshimenting=findViewById(R.id.shiyanshimenting);
        shebeidongligui=findViewById(R.id.shebeidongligui);
        kufangpeidianxiang=findViewById(R.id.kufangpeidianxiang);
        xinzhanbiandianshi=findViewById(R.id.xinzhanbiandianshi);
        chufangneidianxiang=findViewById(R.id.chufangneidianxiang);
        //用户
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqOfficetestProduceElectricity/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!data.isNull("id") && data.getString("factory").equals(factory)) {
                                zongdiankongxiang.setHint(data.getString("receptionRoom"));
                                jizhuangxiangsushe_yiceng.setHint(data.getString("containerDormitoryFirst"));
                                jizhuangxiangsushe_erceng.setHint(data.getString("containerDormitorySecond"));
                                jizhuangxiangsushe_sanceng_dong.setHint(data.getString("containerDormitoryThreeEast"));
                                jizhuangxiangsushe_sanceng_xi.setHint(data.getString("containerDormitoryThreeWest"));
                                shiyanshimenting.setHint(data.getString("rdLaboratory"));
                                bangongshi1.setHint(data.getString("thirdFloorOfficeOne"));
                                bangongshi2.setHint(data.getString("thirdFloorOfficeTwo"));
                                bangongshi3.setHint(data.getString("thirdFloorOfficeThree"));
                                bangongshi4.setHint(data.getString("thirdFloorOfficeFour"));
                                shebeidongligui.setHint(data.getString("equipmentCenter"));
                                kufangpeidianxiang.setHint(data.getString("powerDistributionBox"));
                                xinzhanbiandianshi.setHint(data.getString("substationNewStation"));
                                chufangneidianxiang.setHint(data.getString("electricBoxKitchen"));
                                Toast.makeText(BangongShiyanYongdian.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(BangongShiyanYongdian.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    //    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseDate(View view) {
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                worm_incoming_incomeDate.setText(new StringBuilder()
                        .append(year)
                        .append("-")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("-")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            },
                    HOUR, MINUTE, true).show();
        },
                YEAR, MONTH, DAY).show();
    }
    //提交按钮
    public void save(View view) {
        if (zongdiankongxiang.getText().toString().equals("")) {
            Toast.makeText(this, "请填写接待室设备中心总电控箱读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jizhuangxiangsushe_yiceng.getText().toString().equals("")) {
            Toast.makeText(this, "请填写集装箱宿舍一层电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jizhuangxiangsushe_erceng.getText().toString().equals("")) {
            Toast.makeText(this, "请填写集装箱宿舍二层电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jizhuangxiangsushe_sanceng_dong.getText().toString().equals("")) {
            Toast.makeText(this, "请填写集装箱宿舍三层（东)电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jizhuangxiangsushe_sanceng_xi.getText().toString().equals("")) {
            Toast.makeText(this, "请填写集装箱宿舍三层（西)电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (shiyanshimenting.getText().toString().equals("")) {
            Toast.makeText(this, "请填写研发部实验室门厅电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (bangongshi1.getText().toString().equals("")) {
            Toast.makeText(this, "请填写三楼集装箱办公室1电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (bangongshi2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写三楼集装箱办公室2电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (bangongshi3.getText().toString().equals("")) {
            Toast.makeText(this, "请填写三楼集装箱办公室3电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (shebeidongligui.getText().toString().equals("")) {
            Toast.makeText(this, "请填写设备中心动力柜电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (bangongshi4.getText().toString().equals("")) {
            Toast.makeText(this, "请填写三楼集装箱办公室4电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (kufangpeidianxiang.getText().toString().equals("")) {
            Toast.makeText(this, "请填写站内库房配电箱读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (xinzhanbiandianshi.getText().toString().equals("")) {
            Toast.makeText(this, "请填写新站变电室电表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (chufangneidianxiang.getText().toString().equals("")) {
            Toast.makeText(this, "请填写厨房内电箱读数", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定提交吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消提交", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqOfficetestProduceElectricity/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(BangongShiyanYongdian.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(BangongShiyanYongdian.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(BangongShiyanYongdian.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date", worm_incoming_incomeDate.getText().toString());
                            map.put("reception_room", zongdiankongxiang.getText().toString());
                            map.put("container_dormitory_first", jizhuangxiangsushe_yiceng.getText().toString());
                            map.put("container_dormitory_second", jizhuangxiangsushe_erceng.getText().toString());
                            map.put("container_dormitory_three_east", jizhuangxiangsushe_sanceng_dong.getText().toString());
                            map.put("container_dormitory_three_west", jizhuangxiangsushe_sanceng_xi.getText().toString());
                            map.put("rd_laboratory", shiyanshimenting.getText().toString());
                            map.put("third_floor_office_one", bangongshi1.getText().toString());
                            map.put("third_floor_office_two", bangongshi2.getText().toString());
                            map.put("third_floor_office_three", bangongshi3.getText().toString());
                            map.put("third_floor_office_four", bangongshi4.getText().toString());
                            map.put("equipment_center", shebeidongligui.getText().toString());
                            map.put("power_distribution_box", kufangpeidianxiang.getText().toString());
                            map.put("substation_new_station", xinzhanbiandianshi.getText().toString());
                            map.put("electric_box_kitchen", chufangneidianxiang.getText().toString());
                            map.put("reader",name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}